//
//  GlobalUtils.m
//  YouShaQi
//
//  Created by admin on 12-9-7.
//  Copyright (c) 2012年 HangZhou RuGuo Network Technology Co.Ltd. All rights reserved.
//
#import <QuartzCore/QuartzCore.h>
#import "GlobalUtils.h"
#import "YouShaQiAppDelegate.h"
#import "UmengUtils.h"
#import "OBCConvertor.h"
#import "CustomUrlUtils.h"
#import "FBEncryptorAES.h"
#import <UMMobClick/MobClick.h>
#import "ZSConfigUtil.h"

@implementation GlobalUtils

//***********创建自定义背景图的navigationBar
+ (UINavigationBar *)createHomePageNavigationBarWithRedColor:(UIImage *)titleImage withWidth:(CGFloat)viewWidth
{
    CGFloat navHeight = 64;
    UINavigationBar *customNavigationBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, viewWidth, navHeight)];
    
    UIView *navigationBarBackgroundView = [[UIView alloc] initWithFrame:customNavigationBar.bounds];
    navigationBarBackgroundView.backgroundColor = [ColorThemeUtils getColorWithOriginColor:[[ZSAppPlanUtils colorPlan] appThemeColor] colorTag:ColorThemeRedBar];
    [customNavigationBar addSubview:navigationBarBackgroundView];
    
    UIView *naviBottomLine = [[UIView alloc] initWithFrame:CGRectMake(0, navHeight - 0.5f, viewWidth, 0.5f)];
    naviBottomLine.backgroundColor = [ColorThemeUtils getColorWithOriginColor:RGBCOLOR(133, 11, 11) colorTag:ColorThemeLine];
    [customNavigationBar addSubview:naviBottomLine];
    
    UIImageView* titleImageView = [[UIImageView alloc] initWithImage:titleImage];
    titleImageView.frame = CGRectMake(customNavigationBar.frame.size.width/2-titleImage.size.width, customNavigationBar.frame.size.height/2-titleImage.size.height, titleImage.size.width, titleImage.size.height);
	UINavigationItem *navigationTitle = [[UINavigationItem alloc] init];
    navigationTitle.titleView = titleImageView;
	[customNavigationBar pushNavigationItem:navigationTitle animated:NO];
	
	return customNavigationBar;
}

//创建二级导航按钮
+ (UIButton *)createSecondaryNavBtn:(CGRect)frame withTitle:(NSString *)title
{
    UIButton *navBtn = [[UIButton alloc] initWithFrame:frame];
    UILabel *navLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 15, CGRectGetWidth(frame), 14)];
    navLabel.tag = 99;
    navLabel.text = title;
    navLabel.textColor = [ColorThemeUtils getColorWithOriginColor:RGBCOLOR(85, 85, 85) colorTag:ColorThemeTitle];
    navLabel.font = [UIFont systemFontOfSize:12.0f];
    navLabel.backgroundColor = [UIColor clearColor];
//    navLabel.shadowColor = [UIColor colorWithWhite:0 alpha:0.5f];
//    navLabel.shadowOffset = CGSizeMake(0.0f, 1.0f);
    navLabel.textAlignment = NSTextAlignmentCenter;
    [navBtn addSubview:navLabel];
    
    if ([ColorThemeUtils isNightMode]) {
        [navBtn setBackgroundImage:ImageNamed(@"new_nav_night_normal.png") forState:UIControlStateNormal];
        [navBtn setBackgroundImage:ImageNamed(@"new_nav_night_hilighted.png") forState:UIControlStateHighlighted];
        [navBtn setBackgroundImage:ImageNamed(@"new_nav_night_selected.png") forState:UIControlStateSelected];
        [navBtn setBackgroundImage:ImageNamed(@"new_nav_night_selected.png") forState:UIControlStateSelected|UIControlStateHighlighted];
    } else {
        [navBtn setBackgroundImage:ImageNamed(@"new_nav_normal.png") forState:UIControlStateNormal];
        [navBtn setBackgroundImage:ImageNamed(@"new_nav_hilighted.png") forState:UIControlStateHighlighted];
        [navBtn setBackgroundImage:ImageNamed(@"new_nav_selected.png") forState:UIControlStateSelected];
        [navBtn setBackgroundImage:ImageNamed(@"new_nav_selected.png") forState:UIControlStateSelected|UIControlStateHighlighted];
    }
    
    return navBtn;
}

+ (void)refreshSecondaryNavBtn:(UIButton *)navBtn
{
    [(UILabel *)[navBtn viewWithTag:99] setTextColor:[ColorThemeUtils getColorWithOriginColor:RGBCOLOR(85, 85, 85) colorTag:ColorThemeTitle]];
    if ([ColorThemeUtils isNightMode]) {
        [navBtn setBackgroundImage:ImageNamed(@"new_nav_night_normal.png") forState:UIControlStateNormal];
        [navBtn setBackgroundImage:ImageNamed(@"new_nav_night_hilighted.png") forState:UIControlStateHighlighted];
        [navBtn setBackgroundImage:ImageNamed(@"new_nav_night_selected.png") forState:UIControlStateSelected];
        [navBtn setBackgroundImage:ImageNamed(@"new_nav_night_selected.png") forState:UIControlStateSelected|UIControlStateHighlighted];
    } else {
        [navBtn setBackgroundImage:ImageNamed(@"new_nav_normal.png") forState:UIControlStateNormal];
        [navBtn setBackgroundImage:ImageNamed(@"new_nav_hilighted.png") forState:UIControlStateHighlighted];
        [navBtn setBackgroundImage:ImageNamed(@"new_nav_selected.png") forState:UIControlStateSelected];
        [navBtn setBackgroundImage:ImageNamed(@"new_nav_selected.png") forState:UIControlStateSelected|UIControlStateHighlighted];
    }
}

//设置刷新时间
+ (NSString *)updateRefreshTime:(NSString *)refreshTitle
{
    NSString *refreshTime = [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970] * 1000];
    [UserDefaults setObject:refreshTime forKey:refreshTitle];
    [UserDefaults synchronize];
    return refreshTime;
}

//获取个人信息状态
+ (BOOL)getUserInfoStatus
{
    return [UserDefaults objectForKey:@"userInfoNeedUpdate"] ? [UserDefaults boolForKey:@"userInfoNeedUpdate"] : NO;
}

//标记个人信息需要刷新
+ (void)updateUserInfoStatus:(BOOL)status
{
    [UserDefaults setBool:status forKey:@"userInfoNeedUpdate"];
    [UserDefaults synchronize];
}


//广告跳转
+ (void)customOpenUrl:(NSString *)urlStr
{
    if ([urlStr rangeOfString:@"/mac"].location != NSNotFound) {
        NSString *newUrlStr = [NSString stringWithFormat:@"%@&idfa=%@&mac=%@&random=%f", urlStr, [UmengUtils idfaString], [UmengUtils macString], [[NSDate date] timeIntervalSince1970]];
        newUrlStr = [newUrlStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:newUrlStr]];
    } else {
        urlStr = [urlStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
    }
}


//应用评价经验增加
+ (void)addUserExpRequestByRateApp
{
    if ([LocalUserInfoUtils userLoggedIn]) {
        NSString *urlStr = @"/user/add-exp-week";
        NSDictionary *params = @{@"token": [LocalUserInfoUtils getUserToken],
                                 @"type": @"rate"};
        
        [CustomRequestUtils createNewPostRequest:urlStr params:params success:^(id responseObject) {
            NSLog(@"成功添加评价积分");
        } failure:^(NSError *error) {
            NSLog(@"成功添加评价积分");
        }];
    }
}

//获取当前网络状况
+ (NSString *)getCurrentNet
{
    NSString *result;
    if ([[AFNetworkReachabilityManager sharedManager] isReachable]) {
        if ([[AFNetworkReachabilityManager sharedManager] isReachableViaWiFi]) {
            result = @"wifi";
        } else {
            result = @"3g";
        }
    }
    return result;
}


//自定义pushView
+ (void)customPushViewControllerWithVC:(UIViewController *)currentVC destinationVC:(UIViewController *)destinationVC
{
    if (![[UIApplication sharedApplication] isIgnoringInteractionEvents]) {
        [currentVC.navigationController pushViewController:destinationVC animated:YES];
    }
}

//自定义presentView
+ (void)customPresentViewControllerWithVC:(UIViewController *)currentVC destinationVC:(UIViewController *)destinationVC
{
    if (![[UIApplication sharedApplication] isIgnoringInteractionEvents]) {
        [currentVC presentViewController:destinationVC animated:YES completion:nil];
    }
}

//当前页面截图
+ (UIImage *)snapshotWithVC:(UIViewController *)VC
{
    CGSize viewSize = [UIScreen mainScreen].bounds.size;
    UIGraphicsBeginImageContextWithOptions(viewSize, NO, [[UIScreen mainScreen] scale]);
    
    if (IOS7) {
        [VC.view drawViewHierarchyInRect:VC.view.bounds afterScreenUpdates:YES];
    } else {
        [VC.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    }
    
    // Read the UIImage object
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

//删除loading图
+ (void)hideAndSetNil:(MBProgressHUD *__strong *)globalProgress
{
    if (*globalProgress && [*globalProgress isKindOfClass:[MBProgressHUD class]] && [*globalProgress superview]) {
        [*globalProgress removeFromSuperview];
        *globalProgress = nil;
    }
}

+ (void)hideProgress:(MBProgressHUD *__strong *)progress withMsg:(NSString *)msg
{
    if (*progress) {
        if (msg) {
            [*progress setLabelText:msg];
            [*progress setMode:MBProgressHUDModeText];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [GlobalUtils hideAndSetNil:progress];
            });
        } else {
            [GlobalUtils hideAndSetNil:progress];
        }
    }
}

//获取父视图的ViewController
+ (UIViewController *)getParentVC:(UIView *)view
{
    UIViewController *parentVC;
    id next = [view nextResponder];
    while(![next isKindOfClass:[UIViewController class]]) {
        next = [next nextResponder];
    }
    if ([next isKindOfClass:[UIViewController class]]) {
        parentVC = (UIViewController *)next;
    }
    return parentVC;
}

//判断是不是网络错误
+ (BOOL)isNetworkError:(NSInteger)errorCode
{
    NSArray *errorCodeArr = @[@-1004, @-1005, @-1009];
    if ([errorCodeArr containsObject:@(errorCode)]) {
        return YES;
    }
    return NO;
}

//判断是不是连接超时
+ (BOOL)isTimedOutError:(NSInteger)errorCode
{
    NSArray *errorCodeArr = @[@-999, @-1001];
    if ([errorCodeArr containsObject:@(errorCode)]) {
        return YES;
    }
    return NO;
}

//获取自定义Item的所有变量名
+ (NSArray *)getAllPropertyNames:(Class)itemClass
{
    unsigned int outCount, i;
    NSMutableArray *propertyArr = [NSMutableArray array];
    objc_property_t *properties = class_copyPropertyList(itemClass, &outCount);
    for(i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        const char *propName = property_getName(property);
        if (propName) {
            NSString *propertyName = [NSString stringWithUTF8String:propName];
            [propertyArr addObject:propertyName];
        }
    }
    free(properties);
    return propertyArr;
}

//消除推送角标
+ (void)removeNotificationBadge
{
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(isRegisteredForRemoteNotifications)]) {
        if ([[UIApplication sharedApplication] isRegisteredForRemoteNotifications]) {
            [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
            [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
        }
    } else {
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    }
}

//简繁转换
+ (NSString *)translateStr:(NSString *)originStr
{
    BOOL traditionalMode = [UserDefaults boolForKey:@"TraditionalMode"];
    
    NSString *translatedStr = traditionalMode ? [[OBCConvertor getInstance] s2t:originStr] : originStr;
    return translatedStr;
}

//获取当前设备方向
+ (UIInterfaceOrientation)getCurrentRealInterfaceOrientationWithVC:(UIViewController *)VC
{
    UIInterfaceOrientation interfaceOrientation = [VC interfaceOrientation];
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    if (orientation == UIDeviceOrientationLandscapeLeft) {
        return interfaceOrientation;
    } else if (orientation == UIDeviceOrientationLandscapeRight) {
        return interfaceOrientation;
    } else if (orientation == UIDeviceOrientationPortrait) {
        return UIInterfaceOrientationPortrait;
    } else {
        return interfaceOrientation;
    }
}

//设置文件夹不被iCloud备份
+ (void)addSkipBackupAttributeToItemAtPath:(NSString *)filePathString
{
    NSURL *URL = [NSURL fileURLWithPath:filePathString];
    if ([[NSFileManager defaultManager] fileExistsAtPath:[URL path]]) {
        NSError *error = nil;
        BOOL success = [URL setResourceValue:[NSNumber numberWithBool:YES]
                                      forKey:NSURLIsExcludedFromBackupKey error:&error];
        if(!success){
            NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
        }
    }
}

//加密秘钥
+ (NSString *)encryptedPassword:(NSString *)originPassword
{
    NSData *keyData = [[NSData alloc] initWithBase64EncodedString:@"dqeM9RaURqJ77b702s5UQg==" options:0];
    NSData *ivData = [[NSData alloc] initWithBase64EncodedString:@"6WwS5EeCG1LROJ0cTlWNgw==" options:0];
    NSData *passwordData = [originPassword dataUsingEncoding:NSUTF8StringEncoding];
    NSData *encryptedData = [FBEncryptorAES encryptData:passwordData key:keyData iv:ivData];
    NSString *encryptedPassword = [encryptedData base64EncodedStringWithOptions:0];
    return encryptedPassword;
}

//利用正则表达式验证
+ (BOOL)isValidateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

//打印视图大小
+ (void)logScreenSizeWithView:(UIView *)view
{
    NSLog(@"====================================");
//    NSLog(@"%@", NSStringFromCGRect([[UIScreen mainScreen] bounds]));
    NSLog(@"%@", NSStringFromCGRect([[UIApplication sharedApplication] keyWindow].frame));
    NSLog(@"%@", NSStringFromCGRect([[UIApplication sharedApplication] keyWindow].bounds));
    NSLog(@"%@", NSStringFromCGRect(view.frame));
    NSLog(@"%@", NSStringFromCGRect(view.bounds));
}

//更新版本过滤变量
+ (void)updateVersionLimitWithValue:(NSString *)value
{
    [UserDefaults setBool:[value boolValue] forKey:@"version_limit"];
    [UserDefaults synchronize];
}

+ (BOOL)versionLimitEnabled
{
    return NO;
//    return [UserDefaults boolForKey:@"version_limit"];
}

//获取标签颜色
+ (UIColor *)getTagColorWithIndex:(NSInteger)index
{
    NSArray *tagColorArrary = @[RGBCOLOR(144, 197, 240),
                                RGBCOLOR(192, 105, 208),
                                RGBCOLOR(246, 188, 126),
                                RGBCOLOR(145, 206, 213),
                                RGBCOLOR(103, 204, 183),
                                RGBCOLOR(231, 143, 143),
                                RGBCOLOR(249, 176, 121)];
    if (index > 5) {
        index = index % 6;
    }
    return tagColorArrary[index];
}

//友盟计数
+ (void)uploadCountEventWithId:(NSString *)eventId label:(NSString *)eventLabel
{
    if (![CustomStringUtils isBlankString:eventId]) {
        if (![CustomStringUtils isBlankString:eventLabel]) {
            [MobClick event:eventId label:eventLabel];
        } else {
            [MobClick event:eventId];
        }
    }
}

//友盟计算
+ (void)uploadCalculateEventWithId:(NSString *)eventId attributes:(NSDictionary *)eventAttributes
{
    if (![CustomStringUtils isBlankString:eventId]) {
        if (eventAttributes && ![eventAttributes isKindOfClass:[NSNull class]]) {
            [MobClick event:eventId attributes:eventAttributes];
        }
    }
}

//获取当前应用类型
+ (NSString *)currentAppType
{
    NSString *bundleId = [[NSBundle mainBundle] bundleIdentifier];
    NSString *currentAppType = @"";
    if ([bundleId isEqualToString:@"com.ZhuiShu.XiaoShuo"]) {
        currentAppType = @"weskit1";
    } else if ([bundleId isEqualToString:@"com.ZhuiShu.QiJian"]) {
        currentAppType = @"weskit2";
    } else {
        currentAppType = @"iphone";
    }
    
    return currentAppType;
}

+ (NSString *)currentUserAgent
{
    NSString *userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]];
    
    if (userAgent) {
        if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) {
            NSMutableString *mutableUserAgent = [userAgent mutableCopy];
            if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) {
                userAgent = mutableUserAgent;
            }
        }
        
        return userAgent;
    } else {
        return @"";
    }
}

+ (void)disableCellLayoutMargin:(UITableView *)tableView
{
    if (IOS9) {
        tableView.cellLayoutMarginsFollowReadableWidth = NO;
    }
}

#pragma mark - AllowCondition Function
//漫画岛变量
+ (BOOL)allowShowComicIsland
{
    BOOL comicislandOn = [UserDefaults boolForKey:@"comicislandOn"];
    
    return [UserDefaults boolForKey:@"showComicIsland"] && comicislandOn;
}

+ (void)updateComicIslandWithStatus:(BOOL)show
{
    [UserDefaults setBool:show forKey:@"showComicIsland"];
}

//登录变量
+ (BOOL)allowShowQuickLogin
{
    if (![UserDefaults valueForKey:@"showQuickLogin"]) {
        return YES;
    }
    return [UserDefaults boolForKey:@"showQuickLogin"];
}

+ (void)updateQuickLoginWithStatus:(BOOL)show
{
    [UserDefaults setBool:show forKey:@"showQuickLogin"];
    [UserDefaults synchronize];
}

//充值类型变量
+ (BOOL)allowShowThirdpartyPay
{
    return [UserDefaults boolForKey:@"showThirdpartyPay"];
}

+ (void)updateThirdpartyPayStatus:(BOOL)show
{
    [UserDefaults setBool:show forKey:@"showThirdpartyPay"];
}

+ (BOOL)containsNewlyInTaskCenter {
    return ([UserDefaults valueForKey:@"versionOfRecentlyEnterTaskCenter"] == nil);
}

+ (void)updateContainsNewlyInTaskCenter:(BOOL)containsNewly {
    if (containsNewly) {
        [UserDefaults removeObjectForKey:@"versionOfRecentlyEnterTaskCenter"];
    } else {
        [UserDefaults setValue:[ZSConfigUtil versionShortCodeWithoutDot] forKey:@"versionOfRecentlyEnterTaskCenter"];
    }
}

// 第三方支付参数
+ (NSArray *)payTypesForMonthOrCharge:(BOOL)isForMonth {
    if ([[UserDefaults valueForKey:@"force_open_third_pay"] boolValue]) {
        if (isForMonth) {
            return @[@"iosAliMonthly", @"iosWeixinMonthly", @"appstoreMonthly"];
        }
        return @[@"iosalipay", @"iosweixinpay", @"appstore"];
    }
    if (isForMonth) {
        return [UserDefaults valueForKey:@"monthlyTypes"];
    }
    return [UserDefaults valueForKey:@"payTypes"];
}

@end
